import logger from "morgan";
import fs from "fs";
import dayjs from "dayjs";
import path from "path";
import * as fileStreamRotator from "file-stream-rotator";
import { Request, Response } from "express";
// 日志文件目录

const logDirectory = path.resolve(__dirname, "../../log");
// 确保日志文件目录存在 没有则创建
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

const accessLogStream = fileStreamRotator.getStream({
  date_format: "YYYY-MM-DD", // 日志文件名格式
  filename: path.resolve(logDirectory,"access-%DATE%.log"), // 日志文件名
  frequency: "daily", // 每天创建一个新的日志文件
  max_logs: "7d", // 保留7天的日志
});
const logConfig = logger(
  (tokens: any, req: Request, res: Response) => {
    const logObj = {
      method: tokens.method(req, res), // 请求方式
      url: tokens.url(req, res), // 请求连接
      status: tokens.status(req, res), // 请求状态
      remote_user: tokens["remote-user"](req, res), // 请求用户
      time: dayjs().format("YYYY-MM-DD HH:mm:ss"), // 请求时间
      response_time: tokens["response-time"](req, res) + "ms", // 请求耗时
      browser: tokens["user-agent"](req, res), // 浏览器
    };
    return JSON.stringify(logObj);
  },
  {
    stream: accessLogStream,
  },
);

export default logConfig;
